package blt.app_core.api.base;


import java.util.HashMap;

import blt.app_core.api.impl.BaseImpl;

public class CoreFactory {

    private static final HashMap<Class<? extends IBaseApi>, IBaseApi> cores;
    private static final HashMap<Class<? extends IBaseApi>, Class<? extends BaseImpl>> coreClasses;

    static {
        cores = new HashMap<>();
        coreClasses = new HashMap<>();
    }


    public static <T extends IBaseApi> T getCore(Class<T> cls) {

        if (cls == null) {
            return null;
        }
        try {
            IBaseApi core = cores.get(cls);
            if (core == null) {
                Class<? extends BaseImpl> implClass = coreClasses.get(cls);
                if (implClass == null) {
                    if (cls.isInterface()) {
//						MLog.error("CoreFactory", "No registered core class for: " + cls.getName());
                        throw new IllegalArgumentException("No registered core class for: " + cls.getName());
                    } else {
//						MLog.error("CoreFactory", "Not interface core class for: " + cls.getName());
                        throw new IllegalArgumentException("Not interface core class for: " + cls.getName());
                    }
                } else {
                    core = implClass.newInstance();
                }

                if (core != null) {
                    cores.put(cls, core);
                    //MLog.debug("CoreFactory", cls.getName() + " created: "
                    //        + ((implClass != null) ? implClass.getName() : cls.getName()));
                }
            }
            return (T) core;
        } catch (Throwable e) {
//			MLog.error("CoreFactory", "getCore() failed for: " + cls.getName(), e);
        }
        return null;
    }

    public static void registerCoreClass(Class<? extends IBaseApi> coreInterface, Class<? extends BaseImpl> coreClass) {

        if (coreInterface == null || coreClass == null) {
            return;
        }

        coreClasses.put(coreInterface, coreClass);
        //MLog.debug("CoreFactory", "registered class " + coreClass.getName() + " for core: " + coreInterface.getName());
    }

    protected static boolean hasRegisteredCoreClass(Class<? extends IBaseApi> coreInterface) {
        if (coreInterface == null) {
            return false;
        } else {
            return coreClasses.containsKey(coreInterface);
        }
    }
}
